package com.whjk.system.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.whjk.core.common.utils.LocalDateTimeUtil;
import com.whjk.core.security.config.FileUploadConfig;
import com.whjk.core.security.uitls.SecurityUtils;
import com.whjk.system.biz.mapper.WhjkPackageRelMapper;
import com.whjk.system.biz.mapper.WhjkPersonMapper;
import com.whjk.system.biz.service.PdfService;
import com.whjk.system.biz.service.WhjkPackageRelService;
import com.whjk.system.biz.service.WhjkPersonService;
import com.whjk.system.biz.service.WhjkTjbgzswhService;
import com.whjk.system.data.constant.CommonConstants;
import com.whjk.system.data.dto.PrintDto;
import com.whjk.system.data.dto.WhjkPersonDto;
import com.whjk.system.data.entity.WhjkPerson;
import com.whjk.system.data.entity.WhjkTjbgzswh;
import com.whjk.system.data.po.RegXmListPo;
import com.whjk.system.data.po.WhjkPackageRelInfoPo;
import com.whjk.system.data.po.WhjkPackageRelPo;
import com.whjk.system.data.uitls.BarCodeUtils;
import com.whjk.system.data.uitls.pdfUtils.GuideReportFooter;
import com.whjk.system.data.uitls.pdfUtils.PdfFont;
import com.whjk.system.data.uitls.pdfUtils.PdfTable;
import com.whjk.system.data.uitls.pdfUtils.TjReportFooter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.whjk.system.data.uitls.pdfUtils.PdfUtils.setParagraph;
import static com.whjk.system.data.uitls.pdfUtils.PdfUtils.setParagraphNull;

/**
 * <p>
 *
 * </p>
 *
 * @author hl
 * @since 2023/7/4/004 16:41
 */
@Slf4j
@Service
public class PdfServiceImpl implements PdfService {
    @Autowired
    WhjkPersonMapper personMapper;
    @Autowired
    WhjkPersonService personService;
    @Autowired
    WhjkPackageRelService packageRelService;
    @Autowired
    WhjkPackageRelMapper packageRelMapper;
    @Autowired
    WhjkTjbgzswhService bgzswhService;
    @Autowired
    FileUploadConfig fileUploadConfig;

    @Override
    public void printBarcode(PrintDto dto, HttpServletResponse response) throws Exception {
        //先查询个人信息
        WhjkPerson printVO = personService.getById(dto.getPersonId());
        List<WhjkPackageRelPo> tjPackageRelList = packageRelService.selectByCheckStatus(new QueryWrapper<>()
                .eq("t1.del_flag", 0)
                .eq("t1.pe_id", dto.getPersonId()));
        // 1.新建document对象，并设置左右上下四边边距  （142,85）
        Document document = new Document(new RectangleReadOnly(142, 100), 0, 0, 0, 0);
        // 2.建立一个书写器(Writer)与document对象关联
        File file = new File(".", "条形单.pdf");
        //  File file = new File("E:\\ccc.pdf");
        // file.createNewFile();
        PdfWriter writer = PdfWriter.getInstance(document, Files.newOutputStream(file.toPath()));
        // 3.打开文档
        document.open();
        tjPackageRelList = tjPackageRelList.stream().filter(f -> !"2".equals(f.getJclx())).collect(Collectors.toList());
        Assert.notNull(tjPackageRelList, "没有打印的条码");
        for (WhjkPackageRelPo f : tjPackageRelList) {
            //生成条形单
            txdImg(printVO.getRegSerialNo(), 50, 10, 20, document);
            //标题： 姓名、性别、年龄   体检项目：尿、体检   落尾：所属项目
            PdfPTable table = PdfTable.createTableSQD(new int[]{1});
            String sex = printVO.getGender().equals("1") ? "男" : "女";
            table.addCell(PdfTable.createCellHeight(printVO.getName() + "  " + sex + "  " + printVO.getAge() + "岁" + "  ", PdfFont.getBold(11), 1, 20, 1, PdfTable.notBor, PdfTable.padding3));
            document.add(table);
            setParagraphNull(55, 0, document);

            PdfPTable table2 = PdfTable.createTableSQD(new int[]{1});
            table2.addCell(PdfTable.createCellBold(f.getZhmc(), 11, 0, 1, PdfTable.notBor, PdfTable.padding7));
            document.add(table2);
            document.newPage();
        }
        //关闭文档
        document.close();
        writer.close();
        returnFileIo(file, response, true);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void printZYD(PrintDto dto, HttpServletResponse response) throws Exception {
        // 1.新建document对象，并设置左右上下四边边距
        Document document = new Document(PageSize.A4, 30, 30, 50, 50);
        // 2.建立一个书写器(Writer)与document对象关联
        File file = new File(".", "指引单.pdf");
        PdfWriter writer = PdfWriter.getInstance(document, Files.newOutputStream(file.toPath()));
        // 页眉/页脚
        writer.setPageEvent(new GuideReportFooter());
        // 3.打开文档
        document.open();
        //打印导检单批量
        for (String id : dto.getPersonIds()) {
            WhjkPersonDto person = personMapper.getByIdVo(new QueryWrapper<>()
                    .eq("t1.id", id));
            log.info("打印导检单用户数据:" + new Gson().toJson(person));
            if ("0".equals(person.getPeStatus()) || "3".equals(person.getPeStatus())) {
                throw new RuntimeException(("0".equals(person.getPeStatus()) ? "预约" : "已总检") + "用户不能打印。");
            }
            List<WhjkPackageRelPo> packageRelVoList = packageRelService.selectByCheckStatus(new QueryWrapper<>()
                    .eq("t1.del_flag", 0)
                    .eq("t1.pe_id", person.getId()));
            //  Assert.isTrue(packageRelVoList.size() != 0, "姓名:" + person.getName() + ",体检号" + person.getRegSerialNo() + "未查询到检查项目");
            WhjkTjbgzswh tjbgzswh = bgzswhService.getOne(new LambdaQueryWrapper<WhjkTjbgzswh>()
                    .eq(WhjkTjbgzswh::getLx, 2));
            if (StringUtils.isBlank(person.getAuditDoctor())) {
                person.setAuditDoctor(SecurityUtils.getUser().getName());
                LocalDateTime now = LocalDateTime.now();
                person.setAuditTime(now);
                person.setPeDate(now);
            }
            person.setPeStatus("2");
            //计入开单医生
            personService.updateById(person);
            if (StringUtils.isNotBlank(dto.getPrintType())) {
                if ("1".equals(dto.getPrintType())) {
                    //系统模板
                    XTMB(person, tjbgzswh, packageRelVoList, document);
                }
            }
        }
        //关闭文档
        document.close();
        returnFileIo(file, response, true);
    }

    /**
     * 系统模板
     */
    private void XTMB(WhjkPersonDto person, WhjkTjbgzswh tjbgzswh, List<WhjkPackageRelPo> packageRelVoList, Document document) throws Exception {
        setParagraph(CommonConstants.HOSPITAL_NAME + "体检指引单", PdfFont.getText(17), 1, document);
        setParagraphNull(5, 5, document);
        setParagraph("登记日期：" + LocalDateTimeUtil.localDateTimeToStr(person.getRegisterTime() == null ? LocalDateTime.now() : person.getRegisterTime(), LocalDateTimeUtil.ALL_FORMAT) + "         ", PdfFont.getFourteenText(), 2, document);
        setParagraphNull(5, 5, document);

/*            //添加医院logo
            String imgNames = tjbgzswhName.getImgUrl();
            //添加用户头像
            String imgName = printVO.getUserImage();
            imgName = StringUtils.isEmpty(imgName) ? imgNames : imgName;
            if (!StringUtils.isEmpty(imgName)) {
                imgName = imgName.substring(imgName.lastIndexOf("/") + 1);
                InputStream in = minioTemplate.getObject(CommonConstants.BUCKET_NAME, imgName);
                Image image = Image.getInstance(getContent(in));
                image.setAlignment(Image.ALIGN_CENTER);
                //依照比例缩放
                // image.scalePercent(15);
                image.scaleAbsolute(108, 100);
                image.setAbsolutePosition(20, PageSize.A4.getHeight() - 113);
                //
                document.add(image);
            }*/
//            Image image = Image.getInstance("C:\\Users\\60207\\Desktop\\ZDlogo.png");

        PdfPTable info = PdfTable.createTable(new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
        info.addCell(PdfTable.createCell("体检编号:", 12, 0, 2));
        info.addCell(PdfTable.createCell(person.getRegSerialNo(), 14, 1, PdfTable.borX, 3));
        info.addCell(PdfTable.createCell("姓名:", 12, 2, 2));
        info.addCell(PdfTable.createCellHeight(person.getName(), 12, 1, 15, 3, PdfTable.borX, PdfTable.paddingNot));
        info.addCell(PdfTable.createCell("性别:", 12, 2, 2));
        String gender = person.getGender().equals("1") ? "男" : "女";
        info.addCell(PdfTable.createCell(gender, 14, 1, PdfTable.borX));
        info.addCell(PdfTable.createCell("年龄:", 12, 2, 2));
        info.addCell(PdfTable.createCell(String.valueOf(person.getAge()), 14, 1, PdfTable.borX));
        info.addCell(PdfTable.createCell("手机号码:", 12, 0, 2));
        info.addCell(PdfTable.createCell(person.getPhone(), 14, 1, PdfTable.borX, 5));
        info.addCell(PdfTable.createCell("身份证号码:", 12, 2, 3));
        info.addCell(PdfTable.createCell(person.getIdCard(), 14, 1, PdfTable.borX, 6));
        info.addCell(PdfTable.createCell("体检套餐:", 12, 0, 2));
        info.addCell(PdfTable.createCell(person.getTcmc(), 14, 1, PdfTable.borX, 6));
        info.addCell(PdfTable.createCell("编号:", 14, 1, 3));
        info.addCell(PdfTable.createCell(" ", 14, 0, 5));
        info.addCell(PdfTable.createCell("联系地址:", 12, 0, 2));
        info.addCell(PdfTable.createCell(person.getAddress(), 14, 0, PdfTable.borX, 8));
        info.addCell(PdfTable.createCell(" ", 14, 0, 6));
        document.add(info);

        txdImg(person.getRegSerialNo(), 40, (int) (PageSize.A4.getWidth() - 200), (int) (PageSize.A4.getHeight() - 220), document);

        setParagraphNull(10, 10, document);

        PdfPTable promptTable = PdfTable.createTable(new int[]{1, 7});
        promptTable.addCell(PdfTable.createCell("温馨提示", 12, 0, PdfTable.borSX));
        promptTable.addCell(PdfTable.createCell(tjbgzswh.getBz(), 12, 0, PdfTable.borSX));
        document.add(promptTable);
        setParagraphNull(5, 5, document);

        List<WhjkPackageRelPo> ysjc = packageRelVoList.stream().filter(data -> "1".equals(data.getJclx())).collect(Collectors.toList());
        List<WhjkPackageRelPo> jyjc = packageRelVoList.stream().filter(data -> "2".equals(data.getJclx())).collect(Collectors.toList());
        List<WhjkPackageRelPo> gnjc = packageRelVoList.stream().filter(data -> "3".equals(data.getJclx())).collect(Collectors.toList());

        Map<String, List<WhjkPackageRelPo>> map = new HashMap<>(6);
        map.put("1", ysjc);
        map.put("2", jyjc);
        map.put("3", gnjc);
        for (int i = 1; i <= 3; i++) {
            List<WhjkPackageRelPo> printVOS = map.get(i + "");
            if (CollectionUtils.isEmpty(printVOS)) {
                continue;
            }
            PdfPTable xmTable = PdfTable.createTable(new int[]{7, 3, 1, 5});
            String name = i == 1 ? "医生检查项目" : i == 2 ? "抽血及其他检验项目" : "功能检查";
            xmTable.addCell(PdfTable.createCell(name, 12, 0, PdfTable.borX, PdfTable.baseColor));
            xmTable.addCell(PdfTable.createCell("检查医生", 12, 0, PdfTable.borX, 2, PdfTable.baseColor));
            xmTable.addCell(PdfTable.createCell("提示信息", 12, 1, PdfTable.borX, PdfTable.baseColor));
            for (WhjkPackageRelPo prvo : printVOS) {
                xmTable.addCell(PdfTable.createCell("□" + prvo.getZhmc(), 12, 0));
                xmTable.addCell(PdfTable.createCell("", 12, 1, PdfTable.borX));
                xmTable.addCell(PdfTable.createCell("", 12, 0));
                xmTable.addCell(PdfTable.createCell(prvo.getTsxx(), 12, 1, PdfTable.notBor));
            }
            document.add(xmTable);
            setParagraphNull(5, 10, document);
        }
        //签字
        setParagraphNull(5, 5, document);
        Paragraph end4 = new Paragraph("本人签字：", PdfFont.getFourteenText());
        end4.setFirstLineIndent(350);
        document.add(end4);
        document.newPage();

    }


    @Override
    public void printBF(String personId, String type, HttpServletResponse response) throws Exception {
        log.info("进入打印pdf报告-----");
        boolean p = StringUtils.isBlank(type) || !type.equals("1");
        WhjkPerson person = personService.getById(personId);
        String reportFileName = "report.pdf";
        // 1.新建document对象，并设置左右上下四边边距
        Document document = new Document(PageSize.A4, 100, 70, 50, 60);
        // 2.建立一个书写器(Writer)与document对象关联
        File file = new File(".", reportFileName);
        //  File file = new File("E:\\ccc.pdf");
        // file.createNewFile();
        String property = System.getProperty("user.dir");
        String substring = property.substring(0, property.indexOf(":") + 1);

        String filename = substring + fileUploadConfig.getUrl() + "/tempfile/yytp";
        // String filename = "E:\\usr\\local\\zsyz\\uploadfile\\tempfile\\yytp";
        PdfWriter writer = PdfWriter.getInstance(document, Files.newOutputStream(file.toPath()));

        writer.setPageEvent(new TjReportFooter(filename));
        String peDate = LocalDateTimeUtil.localDateTimeToStr(person.getPeDate() == null ? LocalDateTime.now() : person.getPeDate(), LocalDateTimeUtil.FORMAT);

        // 3.打开文档
        document.open();
        String s3 = filename + "/3.png";
        File fileImg3 = new File(s3);
        if(fileImg3.exists()){
            Image image = Image.getInstance(s3);
            image.scalePercent(33);
            //image.setLeft();
            //image.scaleAbsolute(50, 50);
            image.setAbsolutePosition(0, 0);
            document.add(image);
        }
        setParagraphNull(220, 200, document);
        PdfPTable t = PdfTable.createTableTotalWidth(new int[]{1, 1}, 150);
        t.addCell(PdfTable.createCellSizeColor("定期体检", 40, 1, PdfTable.notBor, PdfTable.paddingM, PdfTable.Blue));
        t.addCell(PdfTable.createCellSizeColor("关注健康", 40, 1, PdfTable.notBor, PdfTable.paddingM, PdfTable.Blue));
        document.add(t);
        setParagraphNull(10, 10, document);
        PdfPTable table = PdfTable.createTableTotalWidth(new int[]{1, 1}, 370);
        table.addCell(PdfTable.createCell("姓         名:", 20, 2, PdfTable.notBor));
        table.addCell(PdfTable.createCell(person.getName(), 20, 1, PdfTable.borX));
        table.addCell(PdfTable.createCell("性         别:", 20, 2, PdfTable.notBor));
        String gender = person.getGender().equals("1") ? "男" : "女";
        table.addCell(PdfTable.createCell(gender, 20, 1, PdfTable.borX));
        table.addCell(PdfTable.createCell("年         龄:", 20, 2, PdfTable.notBor));
        table.addCell(PdfTable.createCell(String.valueOf(person.getAge()), 20, 1, PdfTable.borX));
        table.addCell(PdfTable.createCell("体检日期:", 20, 2, PdfTable.notBor));

        table.addCell(PdfTable.createCell(peDate, 20, 1, PdfTable.borX));
        table.writeSelectedRows(0, -1, 180, 310, writer.getDirectContent());
        String s2 = filename + "/2.png";
        File fileImg2 = new File(s2);
        if(fileImg2.exists()){
            Image image2 = Image.getInstance(s2);
            image2.scalePercent(30);
            image2.setAbsolutePosition(200, 70);
            document.add(image2);
        }
        PdfPTable table2 = PdfTable.createTable(new int[]{1});
        table2.addCell(PdfTable.createCell("健康咨询电话：0797-8251022", 20, 1, PdfTable.notBor));
        table2.writeSelectedRows(0, -1, 60, 60, writer.getDirectContent());
        document.newPage();


      /*  setParagraph("\n\n体检报告导读提示", PdfFont.getBold2(14), 1, document);
        setParagraphNull(20, 20, document);
        setParagraph("尊敬的" + person.getPersonName() + ":", PdfFont.getTitle(12), 0, document);

        // setParagraphNull(10, 10);
        setParagraph("请您认真阅读本体检报告，如果您对本报告的检查结果有不明之处或有异议，请及时与我们联系感谢您对我中心的信任，并配合我们完成本次医学检查。\n         在此我们特别提醒您，由于医疗技术的局限性以及生物学上存在的个体差异，且您选择的体检项目并未涵盖全身所有器官系统，鉴于任何一次医学检查手段和方法都不具备绝对的特异性和灵敏度 (即不存在100%的可靠和准确)，医生所做出的医学诊断和健康建议仅建立在您本次体检的结果和病史陈述的基础上。此外，体检后未发现异常不说明完全没有潜在隐患，若有疾病症状，请立即就医。\n         为了您的健康，请您注意：\n         1.健康问卷对您的疾病评估、健康风险评估及健康指导起着重要的作用，本着对您自已负责任的态度，请您务必认真填写本次问卷。\n         2.对本次体检发现的健康问题，敬请及时咨询相关医学专家，一方面避免延误疾病治疗，另一方面达到早期干预、促进健康的目的。\n         3.为了将疾病的发生遏制在早期的萌芽中，建议您每年进行一次系统的健康体检，并积极参与到我们的健康管理中来，以最小的投入获取最大的健康效益。\n         为您的健康保驾护航是我们的责任所在，主动健康管理是您需要付出的努力，愿您拥有健康的人生。\n        欢迎您再次光临体检中心", PdfFont.getTitle(12), 0, document);
        setParagraphNull(10, 10, document);
        setParagraph(" 赣州市经开区第二人民医院（湖边镇卫生院）体检中心                   ", PdfFont.getTitle(12), 2, document);
        setParagraphNull(60, 60, document);
        document.newPage();*/
        PdfPTable pTable = PdfTable.createTable(new int[]{1});
        pTable.addCell(PdfTable.createCell("本次检查发现", 14, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorhuis));
        document.add(pTable);
        // setParagraph("本次检查发现", PdfFont.getTitle(14), 0, document);
/*        TInspectionRecord one = tInspectionRecordService.getOne(new LambdaQueryWrapper<TInspectionRecord>()
                .eq(TInspectionRecord::getPersonId, person.getId())
                .eq(TInspectionRecord::getDelFlag, 0));
        List<String> list = new ArrayList<>();
        if (one != null && StringUtils.isNotBlank(one.getHandleOpinion())) {
            List<String> list1 = Arrays.asList(one.getHandleOpinion().split("\n"));
            for (int i = 1; i <= 50; i++) {
                String s = i + ":";
                List<String> collect = list1.stream().filter(f -> f.contains(s)).collect(Collectors.toList());
                if (collect.size() > 0) {
                    list.add(collect.get(0));
                } else {
                    break;
                }
            }
        }
        setParagraph(String.join("\n", list), PdfFont.getTitle(12), 0, 0, PdfTable.paddingZS, document);*/
        setParagraphNull(10, 10, document);
        setParagraph("医院盖章:", PdfFont.getTitle(12), 2, document);
        setParagraph("体检日期:" + peDate, PdfFont.getTitle(12), 2, document);
        document.newPage();

        PdfPTable pTable2 = PdfTable.createTable(new int[]{1});
        pTable2.addCell(PdfTable.createCell("建议", 14, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorhuis));
        document.add(pTable2);
        String handleOpinion = "";
        //    if (one != null) {
        //        handleOpinion = one.getHandleOpinion();
        //   }
        setParagraph(handleOpinion, PdfFont.getTitle(12), 0, document);

        document.newPage();


        PdfPTable pTable3 = PdfTable.createTable(new int[]{1});
        pTable3.addCell(PdfTable.createCell("健康体检结果", 14, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorhuis));
        document.add(pTable3);
        List<RegXmListPo> relXmList = packageRelMapper.getRelXmList(person.getId());
        examine(relXmList, person, document);
        //常见病保健指导
        //guidance(document);
        if (false) {
            document.newPage();
            setParagraph("宫颈/阴道  液基薄层细胞学检查报告", PdfFont.getTitle(14), 0, document);
            setParagraph("方法：", PdfFont.getTitle(12), 0, document);
            setParagraph("样品满意度：", PdfFont.getTitle(12), 0, document);
            setParagraph("鳞状细胞量：", PdfFont.getTitle(12), 0, document);
            setParagraph("□颈管细胞    □化生细胞     □红细胞", PdfFont.getTitle(12), 0, document);
            setParagraph("其他：", PdfFont.getTitle(12), 0, document);
            setParagraph("病原体：", PdfFont.getBold(12), 0, document);
            setParagraph("□滴虫    □真菌    □放线菌   □菌群失调，提示细菌性阴道病 □提示疱疹病毒感染     □其他", PdfFont.getTitle(12), 0, document);
            setParagraph("鳞状上皮细胞：", PdfFont.getBold(12), 0, document);
            setParagraph("□正常  □萎缩  □反应性细胞改变  □非典型鳞状细胞  □低级别鳞状上皮内病变(LSIL)   □高级别鳞状上皮内病变（HSIL）  □鳞状细胞癌（SCC）", PdfFont.getTitle(12), 0, document);
            setParagraph("腺上皮细胞分析：", PdfFont.getBold(12), 0, document);
            setParagraph("□正常  □颈管细胞  □内膜细胞  □非典型腺细胞  □原位腺癌（ALS）  □腺癌", PdfFont.getTitle(12), 0, document);
            setParagraph("细胞学病理学诊断:", PdfFont.getBold(12), 0, document);
            setParagraph("备注:", PdfFont.getBold(12), 0, document);

        }


        //关闭文档
        document.close();
        writer.close();
        //将文件流写入response中
        //  returnFileIo(file, "E:\\aaa.pdf", response, false);
        returnFileIo(file, response, true);
    }
    /**
     * 项目
     *
     * @param relXmList
     * @param register
     * @throws Exception
     */
    private void examine(List<RegXmListPo> relXmList, WhjkPerson register, Document document) throws Exception {
        relXmList = relXmList.stream().filter(f -> !"评价室".equals(f.getKsmc())).collect(Collectors.toList());
        //检查类型（1-医生检查，2-检验项目，3-功能检查）
        List<RegXmListPo> doctorCheck = relXmList.stream().filter(data -> "1".equals(data.getJclx())).collect(Collectors.toList());
        List<RegXmListPo> examineCheck = relXmList.stream().filter(data -> "2".equals(data.getJclx())).collect(Collectors.toList());
        List<RegXmListPo> functionCheck = relXmList.stream().filter(data -> "3".equals(data.getJclx())).collect(Collectors.toList());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        //医生检查
        for (RegXmListPo e : doctorCheck) {
            PdfPTable table1 = PdfTable.createTable(new int[]{1});
            table1.addCell(PdfTable.createCell(e.getZhmc(), 12, 0, PdfTable.borX));
            //   table1.addCell(PdfTable.createCell("检查医生:" + (StrUtil.isNotEmpty(e.getCheckDoctor()) ? e.getCheckDoctor() : "") + "   审核日期:" + (Objects.nonNull(e.getCheckTime()) ? DateUtil.formatDate(e.getCheckTime()) : ""), 11, 2, PdfTable.notBor, PdfTable.paddingM));
            document.add(table1);
            PdfPTable table2 = PdfTable.createTable(new int[]{1, 1, 1});
            table2.addCell(PdfTable.createCellSizeColor("项目名称", 11, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCellSizeColor("检查结果", 11, 1, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCell("", 11, 1, PdfTable.notBor, PdfTable.paddingM));
            List<WhjkPackageRelInfoPo> list = packageRelMapper.selecttjxm(new QueryWrapper<>().eq("t1.del_flag", 0)
                    .eq("t1.zhxm_id", e.getXmId())
                    .eq("t1.pe_id", register.getId()));
            for (int i = 0; i < list.size(); i++) {
                if (i % 2 == 0) {
                    table2.addCell(PdfTable.createCell(list.get(i).getXmmc(), 11, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorBlue));
                    table2.addCell(PdfTable.createCell(list.get(i).getCheckResult(), 11, 1, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorBlue));
                    table2.addCell(PdfTable.createCell(list.get(i).getDw(), 11, 1, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorBlue));
                } else {
                    table2.addCell(PdfTable.createCell(list.get(i).getXmmc(), 11, 0, PdfTable.notBor, PdfTable.paddingM));
                    table2.addCell(PdfTable.createCell(list.get(i).getCheckResult(), 11, 1, PdfTable.notBor, PdfTable.paddingM));
                    table2.addCell(PdfTable.createCell(list.get(i).getDw(), 11, 1, PdfTable.notBor, PdfTable.paddingM));
                }
            }
            document.add(table2);
            PdfPTable table4 = PdfTable.createTable(new int[]{1, 2, 2, 2, 2});
            table4.addCell(PdfTable.createCell("", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell("", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell("检查日期:" + (e.getCheckTime() != null ? simpleDateFormat.format(e.getCheckTime()) : ""), 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell("检查者:", 12, 2, PdfTable.notBor, PdfTable.paddingM));
            String s1 = org.apache.commons.lang3.StringUtils.isNotBlank(e.getCheckDoctor()) ? e.getCheckDoctor() : "";
            table4.addCell(PdfTable.createCell(s1, 12, 0, PdfTable.notBor, PdfTable.paddingM));
            document.add(table4);
            PdfPTable table3 = PdfTable.createTable(new int[]{1});
            table3.addCell(PdfTable.createCell("小结:   " + (org.springframework.util.StringUtils.isEmpty(e.getSummarize()) ? "未见异常" : e.getSummarize()), 11, 0, PdfTable.notBor, PdfTable.paddingM));
            document.add(table3);
        }
        List<String> jyList = new ArrayList<>();
        //检验项目
        for (RegXmListPo e : examineCheck) {
            PdfPTable table1 = PdfTable.createTable(new int[]{1});
            table1.addCell(PdfTable.createCell(e.getZhmc(), 12, 0, PdfTable.borX));
            document.add(table1);
            PdfPTable table2 = PdfTable.createTable(new int[]{2, 1, 1, 1, 1});
/*                List<TjZdjgbg> list = tjZdjgbgMapper.selecttjxm(new QueryWrapper<>()
                        .eq("t1.DEL_FLAG", 0)
                        .eq("t1.ZHXM_ID", e.getXmId())
                        .eq("t1.REG_ID", printDTO.getReId()));*/
            List<WhjkPackageRelInfoPo> list = packageRelMapper.selecttjxm(new QueryWrapper<>()
                    .eq("t1.del_flag", 0)
                    .eq("t1.rel_id", e.getRegItemId())
                    .eq("t1.pe_id", register.getId()));
            table2.addCell(PdfTable.createCellSizeColor("项目名称", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCellSizeColor("检查结果", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCellSizeColor("单位", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCellSizeColor("参考值", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCellSizeColor("提示", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            list.forEach(f -> {
                String isAbnormal = "";
                if ("1".equals(f.getIsAbnormal())) {
                    isAbnormal = "不正常";
                } else if ("2".equals(f.getIsAbnormal())) {
                    isAbnormal = "↑↑";
                } else if ("3".equals(f.getIsAbnormal())) {
                    isAbnormal = "↓↓";
                } else if ("4".equals(f.getIsAbnormal())) {
                    isAbnormal = "↑↑↑";
                } else if ("5".equals(f.getIsAbnormal())) {
                    isAbnormal = "↓↓↓";
                } else if ("6".equals(f.getIsAbnormal())) {
                    isAbnormal = "↑";
                } else if ("7".equals(f.getIsAbnormal())) {
                    isAbnormal = "↓";
                }
                table2.addCell(PdfTable.createCell(f.getXmmc(), 12, 0, PdfTable.notBor, PdfTable.paddingM, "".equals(isAbnormal) ? null : PdfTable.baseColorLightRed));
                table2.addCell(PdfTable.createCell(f.getCheckResult(), 12, 0, PdfTable.notBor, PdfTable.paddingM, "".equals(isAbnormal) ? null : PdfTable.baseColorLightRed));
                table2.addCell(PdfTable.createCell(f.getDw(), 12, 0, PdfTable.notBor, PdfTable.paddingM, "".equals(isAbnormal) ? null : PdfTable.baseColorLightRed));
                String szxx = org.springframework.util.StringUtils.isEmpty(f.getSzxx()) ? "" : f.getSzxx();
                String szsx = org.springframework.util.StringUtils.isEmpty(f.getSzsx()) ? "" : f.getSzsx();
                table2.addCell(PdfTable.createCell(szxx + "-" + szsx, 12, 0, PdfTable.notBor, PdfTable.paddingM, "".equals(isAbnormal) ? null : PdfTable.baseColorLightRed));
                table2.addCell(PdfTable.createCell(isAbnormal, 12, 0, PdfTable.notBor, PdfTable.paddingM, "".equals(isAbnormal) ? null : PdfTable.baseColorLightRed));
            });
            document.add(table2);
            PdfPTable table3 = PdfTable.createTable(new int[]{1});
            table3.addCell(PdfTable.createCell("小结:   " + (org.springframework.util.StringUtils.isEmpty(e.getSummarize()) ? "未见异常" : e.getSummarize()), 12, 0, PdfTable.notBor, PdfTable.paddingM));
            document.add(table3);
            PdfPTable table4 = PdfTable.createTable(new int[]{1, 2, 2, 2, 2});
            table4.addCell(PdfTable.createCell("检查者:", 12, 2, PdfTable.notBor, PdfTable.paddingM));
            String s2 = org.apache.commons.lang3.StringUtils.isNotBlank(e.getCheckDoctor()) ? e.getCheckDoctor() : "";
            table4.addCell(PdfTable.createCell(s2, 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell("检查日期:" + (e.getCheckTime() != null ? simpleDateFormat.format(e.getCheckTime()) : ""), 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell("审查者:", 12, 2, PdfTable.notBor, PdfTable.paddingM));
            String s33 = org.apache.commons.lang3.StringUtils.isNotBlank(e.getReviewDoctor()) ? e.getReviewDoctor() : "";
            table4.addCell(PdfTable.createCell(s33, 12, 0, PdfTable.notBor, PdfTable.paddingM));
            if (org.apache.commons.lang3.StringUtils.isNotBlank(e.getStudyNo())) {
                jyList.add(e.getStudyNo());
            }
            document.add(table4);
        }

        List<String> pacsList = new ArrayList<>();
        List<String> xdtList = new ArrayList<>();
        List<String> syjList = new ArrayList<>();
        List<String> miniIoList = new ArrayList<>();
        List<String> dctList = new ArrayList<>();
        List<String> fgnList = new ArrayList<>();
        List<String> gmdList = new ArrayList<>();
        //功能检查
        for (RegXmListPo e : functionCheck) {
            //  String s = "0".equals(e.getCheckStatus()) ? "未检查" : "1".equals(e.getCheckStatus()) ? "" : "弃检";
            PdfPTable table1 = PdfTable.createTable(new int[]{1});
            table1.addCell(PdfTable.createCell(e.getZhmc(), 12, 0, PdfTable.borX));
            document.add(table1);
            /*List<TjZdjgbg> list = tjZdjgbgMapper.selecttjxm(new QueryWrapper<>()
                    .eq("t1.DEL_FLAG", 0)
                    .eq("t1.ZHXM_ID", e.getXmId())
                    .eq("t1.REG_ID", printDTO.getReId()));*/
            PdfPTable table2 = PdfTable.createTable(new int[]{1, 7});
            table2.addCell(PdfTable.createCellSizeColor("检查部位: ", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCell("[" + e.getCheckPart() + "]", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table2.addCell(PdfTable.createCellSizeColor("检查所见: ", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCell("", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table2.addCell(PdfTable.createCell("", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table2.addCell(PdfTable.createCell(e.getAuxiliaraResult(), 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.leading));
            table2.addCell(PdfTable.createCellSizeColor("诊断意见: ", 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.baseColorRed));
            table2.addCell(PdfTable.createCell("", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table2.addCell(PdfTable.createCell("", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table2.addCell(PdfTable.createCell(e.getSummarize(), 12, 0, PdfTable.notBor, PdfTable.paddingM, PdfTable.leading));
            document.add(table2);
            PdfPTable table4 = PdfTable.createTable(new int[]{1, 2, 2, 3, 2, 2});
            table4.addCell(PdfTable.createCell("", 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell("报告医师:", 12, 2, PdfTable.notBor, PdfTable.paddingM));
            String s2 = org.apache.commons.lang3.StringUtils.isNotBlank(e.getCheckDoctor()) ? e.getCheckDoctor() : "";
            table4.addCell(PdfTable.createCell(s2, 12, 0, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell("检查日期:" + (e.getCheckTime() != null ? simpleDateFormat.format(e.getCheckTime()) : ""), 12, 0, PdfTable.notBor, PdfTable.paddingM));

            table4.addCell(PdfTable.createCell("审核医师:", 12, 2, PdfTable.notBor, PdfTable.paddingM));
            table4.addCell(PdfTable.createCell(s2, 12, 0, PdfTable.notBor, PdfTable.paddingM));

            document.add(table4);

        }
        document.newPage();

    }


    /**
     * 生成txd图片放到页面固定位置
     *
     * @param number
     * @param percent
     * @param absX
     * @param absY
     */
    private void txdImg(String number, int percent, int absX, int absY, Document document) {
        //生成条形码图片，然后转换成流
        BufferedImage imagebu = BarCodeUtils.insertWords(BarCodeUtils.getBarCode(number), number);
        File picFile = new File(".", number + ".jpg");
        InputStream imgInputStream;
        try {
            ImageIO.write(imagebu, "jpg", picFile);
            imgInputStream = Files.newInputStream(picFile.toPath());
            byte[] bytes = getContent(imgInputStream);
            if (bytes != null) {
                Image image = Image.getInstance(bytes);
                image.setAlignment(Image.ALIGN_CENTER);
                //依照比例缩放
                image.scalePercent(percent);
                image.setAbsolutePosition(absX, absY);
                document.add(image);
            }
            imgInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            picFile.delete();
        }
    }

    /**
     * InputStream 转 byte[]
     *
     * @param is
     * @return
     */
    public static byte[] getContent(InputStream is) {
        if (is == null) {
            return null;
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            //byte[] buffer = new byte[16 * 1024];
            while (true) {
                int len = is.read(buffer);
                if (len == -1) {
                    break;
                }
                baos.write(buffer, 0, len);
            }
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return baos.toByteArray();
    }

    private void returnFileIo(File file, HttpServletResponse response, boolean delFileFlag) {
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);

            //设置文件ContentType类型
            response.setContentType("application/octet-stream");

            response.addHeader("Content-Length", String.valueOf(file.length()));

            //response.setContentType("application/pdf");
//            //设置文件头：最后一个参数是设置下载文件名
//            response.setHeader("Content-Disposition",
//                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("pdf文件流返回失败");
        } finally {
            try {
                out.close();
                in.close();
            } catch (Exception e) {
                log.error("关闭流失败");
            }
            if (file != null && delFileFlag) {
                file.delete();
            }
        }
    }
}
